package leo.peersim.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Calendar;

public class FileLoggerService {
	
	private Object _client;
	private OutputStreamWriter out;
	
	public FileLoggerService(Object client, String customString) throws IOException {
		this._client = client;
		
		File f = new File(new File("log"), this.getLogFileName(this._client) + "_" + customString);
		FileOutputStream fos = new FileOutputStream(f);
		out = new OutputStreamWriter(fos, "UTF-8");
	}
	
	public boolean log(String line) {
		try {
			out.write(line + "\n");
			return true;
		} catch (IOException e) {
			return false;
		}
	}
	
	public void closeStream() throws IOException {
		out.close();
	}
	
	/**
	 * 
	 * @return fileName to be used for the log
	 */
	private String getLogFileName(Object caller) {
		Calendar cal = Calendar.getInstance();
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyMMddHHmmss");
	    String date = sdf.format(cal.getTime());
	    
	    String classname = caller.getClass().getName();
	    //String splittedClassname[] = classname.split("\\.");
	    //String shortClassname = splittedClassname[splittedClassname.length-1];
	    return date + "_" + classname;
	}

}
